package cn.aylog.springboot.listener;

import cn.aylog.springboot.entity.Subject;
import cn.aylog.springboot.entity.SubjectExcelVo;
import cn.aylog.springboot.service.ISubjectService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectReadListener implements ReadListener<SubjectExcelVo> {

    private ISubjectService subjectService;

    public SubjectReadListener() {
    }

    public SubjectReadListener(ISubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectExcelVo subjectExcelVo, AnalysisContext analysisContext) {
        Subject levelOne = this.levelOneSubject(subjectExcelVo.getLevelOneName());
        if(null == levelOne) {
            levelOne = new Subject();
            levelOne.setTitle(subjectExcelVo.getLevelOneName());
            subjectService.save(levelOne);
        }

        Subject levelTwo = this.levelTwoSubject(subjectExcelVo.getLevelTwoName(), levelOne.getId());
        if(null == levelTwo) {
            levelTwo = new Subject();
            levelTwo.setTitle(subjectExcelVo.getLevelTwoName());
            levelTwo.setParentId(levelOne.getId());
            subjectService.save(levelTwo);
        }
    }

    private Subject levelOneSubject(String title) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("title", title);
        wrapper.eq("parent_id", "0");
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }

    private Subject levelTwoSubject(String title, String pid) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("title", title);
        wrapper.eq("parent_id", pid);
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
